package leetCode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

public class Q103 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        /**
         * 定义一个 orient 0向右 1向左
         * 定义两个队列，
         */
        List<List<Integer>> res = new ArrayList<>();

        ArrayDeque<TreeNode> queue = new ArrayDeque<>();

        int ori = 0;

        if(root!=null){
            queue.add(root);
        }

        while (!queue.isEmpty()){
            int n = queue.size();
            List<Integer> level = new ArrayList<>();
            /**
             * 如果0，从头向尾弹出访问，依次把左右儿子添加入队列尾
             * 如果1，从尾向头弹出访问，依次把右左儿子添加入队列头
             * 更新朝向
             */

            if(ori == 0){
                for(int i=0;i<n;i++){
                    TreeNode node = queue.poll();
                    level.add(node.val);
                    if (node.left != null) {
                        queue.add(node.left);
                    }
                    if (node.right != null) {
                        queue.add(node.right);
                    }
                }
            }else {
                for(int i=0;i<n;i++){
                    TreeNode node = queue.pollLast();
                    level.add(node.val);
                    if (node.right != null) {
                        queue.addFirst(node.right);
                    }
                    if (node.left != null) {
                        queue.addFirst(node.left);
                    }
                }
            }
            res.add(level);
            ori = (ori == 0) ? 1 : 0;
        }

        return res;
    }
}
